package com.myutil.utils.email;

import java.net.URL;
import java.util.Set;
import java.util.TreeSet;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.HtmlEmail;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;


public class EmailUtil {
	public static void sendEmail(String subject,String html, JSONObject notify ) {
		if(notify==null) {
			return ;
		}

		//JSONObject notify = config.getJSONObject("notify");
		String to = notify.getString("to");
		
		JSONObject emailConfigJson = notify.getJSONObject("emailConfig");
		
		SendEmailRequest req = new SendEmailRequest();
		req.setSubject(subject);
		req.setHtml(html);
		req.setTo(to);
		
		EmailConfig emailConfig = JSON.toJavaObject(emailConfigJson, EmailConfig.class); 
		EmailUtil.send(req,emailConfig);
		System.out.println("发送邮件 给"+to+"  主题:"+subject+" 内容:"+html);
		
	}
	
	// 去除重复,split,trim
	static private Set<String> splitAndTrim(String str) {
		Set<String> set = new TreeSet<>();
		if (str != null) {
			String[] splittedStrings = str.split(",");
			for (int i = 0; i < splittedStrings.length; i++) {
				splittedStrings[i] = splittedStrings[i].trim();
				if (!StringUtils.isEmpty(splittedStrings[i])) {
					set.add(splittedStrings[i]);
				}
			}
		}
		return set;
	}
	
	public static Integer send(SendEmailRequest req,EmailConfig config) {

		try {
			// 发送简单的email,不能添加附件
			HtmlEmail email = new HtmlEmail();
			// 邮件服务器域名
			email.setHostName(config.getHost());
			// 用户名和密码为邮箱的账号及授权码
			email.setAuthentication(config.getUsername(), config.getPassword());
			// email.setAuthenticator("用户名", "密码");

			email.setSmtpPort(config.getPort());

			email.setSSLOnConnect(config.getUseSSL());
			email.setStartTLSEnabled(config.getUseTLS());

			// 设置字符编码方式
			email.setCharset(StringUtils.isEmpty(req.getCharset())?"UTF-8":req.getCharset());
			// 发件人
			email.setFrom(StringUtils.isEmpty(req.getFrom())?config.getUsername():req.getFrom());
			// 收件人
			Set<String> tos = splitAndTrim(req.getTo());
			for (String toEmail : tos) {
				if (!StringUtils.isEmpty(toEmail)) {
					email.addTo(toEmail);
				}
			}
			Set<String> ccs = splitAndTrim(req.getCc());
			for (String ccEmail : ccs) {
				if (!StringUtils.isEmpty(ccEmail)) {
					email.addCc(ccEmail);
				}
			}
			Set<String> bccs = splitAndTrim(req.getBcc());
			for (String bccEmail : bccs) {
				if (!StringUtils.isEmpty(bccEmail)) {
					email.addBcc(bccEmail);
				}
			}

			// 邮件主题
			email.setSubject(req.getSubject());
			// 邮件正文
			email.setMsg(req.getHtml());
			
			if(req.getAttachments()!=null && !req.getAttachments().isEmpty()) {
				for (int i = 0; i < req.getAttachments().size(); i++) {
					EmailAttach att = req.getAttachments().get(i);
					EmailAttachment attachment = new EmailAttachment();
					//attachment.setPath("D:\\MongoDB.txt");// 本地附件，绝对路径
					attachment.setURL(new URL(att.getUrl()));//可添加网络上的附件
					attachment.setDisposition(EmailAttachment.ATTACHMENT);
					attachment.setDescription(att.getDescription());
					attachment.setName(att.getName());// 附件名称
					email.attach(attachment);
				}
			}
			
			// 发送
			email.send();
			//logger.debug("sendEmail res : {}", msgId);

			Integer count = tos.size() + ccs.size() + bccs.size();
			return count;
		} catch (Exception e) {
			//logger.error("发送邮件失败:"+e);
			throw new RuntimeException(e);
		}
	}
}
